package com.ikingtech.platform.service.system.role.service;

import com.ikingtech.framework.sdk.enums.system.role.DataScopeTypeEnum;
import com.ikingtech.framework.sdk.user.api.UserRoleApi;
import com.ikingtech.framework.sdk.user.model.UserRoleDTO;
import com.ikingtech.framework.sdk.utils.Tools;
import com.ikingtech.platform.service.system.role.entity.RoleDataScopeDO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author tie yan
 */
@Service
@RequiredArgsConstructor
public class UserRoleService implements UserRoleApi {

    private final RoleRepository service;

    private final RoleDataScopeRepository roleDataScopeService;

    private final RoleMenuRepository roleMenuService;

    @Override
    public List<UserRoleDTO> loadByIds(List<String> roleIds) {
        if (Tools.Coll.isBlank(roleIds)) {
            return new ArrayList<>();
        }
        List<RoleDataScopeDO> roleDataScopeEntities = this.roleDataScopeService.listByRoleIds(roleIds);
        Map<String, List<String>> dataScopeCodeMap = Tools.Coll.convertGroup(roleDataScopeEntities, RoleDataScopeDO::getRoleId, RoleDataScopeDO::getDataScopeCode);
        return Tools.Coll.convertList(this.service.listByIds(roleIds), entity -> {
            UserRoleDTO userRole = new UserRoleDTO();
            userRole.setRoleId(entity.getId());
            userRole.setRoleName(entity.getName());
            userRole.setRoleDataScopeType(DataScopeTypeEnum.valueOf(entity.getDataScopeType()));
            userRole.setRoleDataScopeCodes(dataScopeCodeMap.get(entity.getId()));
            userRole.setTenantCode(entity.getTenantCode());
            return userRole;
        });
    }

    @Override
    public List<String> loadIdByMenuIds(List<String> menuIds, String tenantCode) {
        if (Tools.Coll.isBlank(menuIds)) {
            return new ArrayList<>();
        }
        return this.roleMenuService.listRoleIdByMenuIds(menuIds, tenantCode);
    }

    @Override
    public List<String> loadIdByMenuId(String menuId, String tenantCode) {
        return this.roleMenuService.listIdByMenuId(menuId, tenantCode);
    }
}
